// sql_view.cpp

#ifndef _SQL_VIEW_CPP_
#define _SQL_VIEW_CPP_


#include"sql_view.h"
#include<fstream>
#include<sstream>
#include"../include/utils.h"



Viewer::ViewKeeper::ViewKeeper(){
    this->view_vis.clear();
    this->allview.clear();
    this->__readData();
}

//查看视图是否存在
//成功1 失败0
int Viewer::ViewKeeper::hasView(const std::string viewname){
    return this->view_vis[viewname] == 1 ? 1 : 0;
}

//添加视图信息
//成功0 失败-1
int Viewer::ViewKeeper::addView(const std::string viewname,const std::string line){
    //已经存在的视图不能重名
    if(this->hasView(viewname)){
        return -1;
    }
    //添加视图
    this->view_vis[viewname] = 1;
    this->allview[viewname] = line;
    return 0;
}

//删除视图信息
int Viewer::ViewKeeper::delView(const std::string viewname){
    if(this->hasView(viewname)){
        this->view_vis[viewname] = 0;
        this->allview.erase(viewname);
    }
    return 0;
}

//获取所有存在的视图
std::vector<std::string> Viewer::ViewKeeper::getAllViewInfo(){
    std::vector<std::string> res;
    std::map<std::string,int>::iterator iter;
    iter = this->view_vis.begin();
    while(iter != this->view_vis.end()){
        if(iter->second == 1){
            res.push_back(iter->first);
        }
        iter++;
    }
    return res;
}

//读取文件数据
int Viewer::ViewKeeper::__readData(){
    std::fstream inner;
    inner.open(this->view_path,std::ios::in);
    this->allview.clear();
    this->view_vis.clear();
    //
    std::string line = "";
    while(getline(inner,line)){
        int lenth = line.size();
        if(lenth == 0){ break; }
        if(line[0] == '#') { break; }
        std::stringstream ss(line);
        std::string vname,vsql;
        ss >> vname;
        getline(ss,vsql);
        vsql = SavenUtils::trim(vsql);
        //
        this->addView(vname,vsql);
    }
    return 0;
}

//向文件写入数据
int Viewer::ViewKeeper::__writeData(){
    std::fstream outer;
    outer.open(this->view_path,std::ios::out);
    //
    std::map<std::string,int>::iterator iter;
    iter = this->view_vis.begin();
    while(iter != this->view_vis.end()){
        std::string vname = iter->first;
        if(iter->second == 1){
            std::string vsql = this->allview[vname];
            outer << vname << " " << vsql << "\n";
        }
        iter++;
    }
    return 0;
}

// //测试所有视图的有效性并删除无效的视图
// //返回被删除的视图的名称与创建sql语句
// std::vector<std::vector<std::string> > Viewer::ViewKeeper::delInvaildView(TBCore::SavenDB_TBCore& rhs){
//     std::vector<std::vector<std::string> > ans;
//     return ans;
// }

// int ViewInit(TableMM::Table& rhs){
    
// }



#endif //_SQL_VIEW_CPP_

